<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <img src="/OIP.webp" alt="小智医疗" class="logo" />
        <h2>注册账号</h2>
        <p class="subtitle">加入小智医疗，开启智能健康管理</p>
      </div>
      
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="realName">
          <el-input
            v-model="registerForm.realName"
            placeholder="请输入真实姓名"
            prefix-icon="UserFilled"
            size="large"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            prefix-icon="Phone"
            size="large"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱地址"
            prefix-icon="Message"
            size="large"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            prefix-icon="Lock"
            size="large"
            show-password
            clearable
            @keyup.enter="handleRegister"
          />
        </el-form-item>
        
        <el-form-item prop="agreement">
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意
            <el-link type="primary" :underline="false">《用户协议》</el-link>
            和
            <el-link type="primary" :underline="false">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="register-button"
            :loading="loading"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
        
        <el-form-item>
          <div class="login-link">
            <span>已有账号？</span>
            <el-link type="primary" @click="$router.push('/login')">
              立即登录
            </el-link>
          </div>
        </el-form-item>
        
        <el-form-item>
          <div class="quick-access">
            <el-divider>或者</el-divider>
            <el-button
              type="success"
              plain
              size="large"
              class="direct-access-button"
              @click="handleDirectAccess"
            >
              直接进入系统
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="medical-icon medical-icon-1">🏥</div>
      <div class="medical-icon medical-icon-2">⚕️</div>
      <div class="medical-icon medical-icon-3">🩺</div>
      <div class="medical-icon medical-icon-4">💊</div>
      <div class="medical-icon medical-icon-5">🧬</div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import { User, UserFilled, Phone, Message, Lock } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const registerFormRef = ref()
const loading = ref(false)

const registerForm = reactive({
  username: '',
  realName: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
  agreement: false
})

// 自定义验证规则
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能少于6位'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else if (!phoneRegex.test(value)) {
    callback(new Error('请输入正确的手机号格式'))
  } else {
    callback()
  }
}

const validateEmail = (rule, value, callback) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (value === '') {
    callback(new Error('请输入邮箱地址'))
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { required: true, validator: validateEmail, trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
  agreement: [
    { 
      type: 'boolean', 
      required: true, 
      message: '请阅读并同意用户协议和隐私政策', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'))
        } else {
          callback()
        }
      }
    }
  ]
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    // 使用Promise处理表单验证
    await new Promise((resolve, reject) => {
      registerFormRef.value.validate((valid, fields) => {
        if (valid) {
          resolve()
        } else {
          // 显示第一个验证错误
          const firstField = Object.keys(fields)[0]
          const firstError = fields[firstField][0].message
          ElMessage.error(firstError)
          reject(fields)
        }
      })
    })
    
    loading.value = true
    const result = await userStore.register(registerForm)
    
    if (result.success) {
      ElMessage.success('注册成功！欢迎使用小智医疗版')
      router.push('/')
    } else {
      ElMessage.error(result.message || '注册失败，请稍后重试')
    }
  } catch (error) {
    if (error && typeof error === 'object' && !error.message) {
      // 这是表单验证错误，已经在上面处理了
      console.log('表单验证失败:', error)
    } else {
      console.error('注册错误:', error)
      ElMessage.error('注册失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 直接进入系统（无需注册）
const handleDirectAccess = () => {
  ElMessage.success('欢迎使用小智医疗系统！')
  router.push('/')
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.register-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  width: 100%;
  max-width: 450px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-height: 90vh;
  overflow-y: auto;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 15px;
  object-fit: cover;
  border: 3px solid #409eff;
}

.register-header h2 {
  color: #2c3e50;
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
}

.subtitle {
  color: #7f8c8d;
  margin: 0;
  font-size: 14px;
}

.register-form {
  margin-top: 20px;
}

.register-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  background: linear-gradient(45deg, #409eff, #67c23a);
  border: none;
}

.register-button:hover {
  background: linear-gradient(45deg, #337ecc, #5daf34);
}

.login-link {
  text-align: center;
  width: 100%;
  color: #7f8c8d;
  font-size: 14px;
}

.quick-access {
  text-align: center;
  margin-top: 10px;
}

.direct-access-button {
  width: 100%;
  height: 40px;
  border-radius: 8px;
  font-weight: 600;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: -1;
}

.medical-icon {
  position: absolute;
  font-size: 60px;
  opacity: 0.1;
  animation: float 6s ease-in-out infinite;
}

.medical-icon-1 {
  top: 5%;
  left: 10%;
  animation-delay: 0s;
}

.medical-icon-2 {
  top: 15%;
  right: 15%;
  animation-delay: 1.2s;
}

.medical-icon-3 {
  bottom: 40%;
  left: 5%;
  animation-delay: 2.4s;
}

.medical-icon-4 {
  bottom: 20%;
  right: 10%;
  animation-delay: 3.6s;
}

.medical-icon-5 {
  top: 50%;
  left: 50%;
  animation-delay: 4.8s;
  transform: translateX(-50%);
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(10deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-container {
    padding: 10px;
  }
  
  .register-card {
    padding: 30px 20px;
    margin: 10px;
    max-height: 95vh;
  }
  
  .logo {
    width: 60px;
    height: 60px;
  }
  
  .register-header h2 {
    font-size: 24px;
  }
  
  .medical-icon {
    font-size: 40px;
  }
}

/* 自定义滚动条 */
.register-card::-webkit-scrollbar {
  width: 6px;
}

.register-card::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.register-card::-webkit-scrollbar-thumb {
  background: rgba(64, 158, 255, 0.5);
  border-radius: 3px;
}

.register-card::-webkit-scrollbar-thumb:hover {
  background: rgba(64, 158, 255, 0.7);
}
</style>